import requests
from typing import Dict, Any
from configs.kb_config import Go_SERVICE_URL_PREFIX


def verify_owner_authorization(uid: int, pet_id: int) -> Dict[str, Any]:
    """
    验证用户授权
    
    参数:
        uid: 用户ID (OwnerUserId)
        pet_id: 访问者ID (AccessorUserId)
    
    返回:
        dict: 包含验证结果的字典
            - success: 请求是否成功
            - has_authorization: 是否开启授权
            - key_valid: 验证是否通过
            - message: 响应消息
            - code: 响应状态码
    """
    url = f"{Go_SERVICE_URL_PREFIX}/admin/user/verifyownerkeyauthorization"
    
    payload = {
        "OwnerUserId": uid,
        "AccessorUserId": pet_id
    }
    
    try:
        response = requests.post(url, json=payload, timeout=10)
        response.raise_for_status()
        
        result = response.json()
        
        if result.get("code") == 200:
            data = result.get("data", {})
            return {
                "success": True,
                "has_authorization": data.get("HasAuthorization", False),
                "key_valid": data.get("KeyValid", False),
                "message": result.get("msg", ""),
                "code": result.get("code")
            }
        else:
            return {
                "success": False,
                "has_authorization": False,
                "key_valid": False,
                "message": result.get("msg", "验证失败"),
                "code": result.get("code")
            }
    
    except requests.exceptions.Timeout:
        return {
            "success": False,
            "has_authorization": False,
            "key_valid": False,
            "message": "请求超时",
            "code": None
        }
    except requests.exceptions.RequestException as e:
        return {
            "success": False,
            "has_authorization": False,
            "key_valid": False,
            "message": f"请求失败: {str(e)}",
            "code": None
        }

